import {authorization, login} from '@/api/user';
import {setToken} from "@/lib/util";

const state = {
	userName: 'Mike',
	rules: {}
};
const getters = {
	firstLetter: (state) => {
		return state.userName.substr(0, 1)
	}
};
const mutations = {
	setUserName(state, params) {
		state.userName = params
	},

	SET_RULES(state,rules) {
		state.rules = rules;
	}
};
const actions = {
	// commit:用来提交一个mutation;
	// state:当前store实例的state;
	// rootState:根实例(index)里的state,可以访问index里state里的值,比如获取appName -> rootState.appName;
	// dispatch:提交action
	updateUserName({commit, state, rootState, dispatch}) {
		// rootState.appName;
	},
	login({commit}, {userName, password}) {
		return new Promise(((resolve, reject) => {
			login({userName, password})
				.then(res => {
					if (res.data.code === 200 && res.data.data.token) {
						setToken(res.data.data.token);
						resolve();
					} else {
						reject(new Error('fail'));
					}
				})
				.catch(error => reject(new Error(error)));
		}))
	},
	authorization({commit}, token) {
		return new Promise(((resolve, reject) => {
			authorization().then(res => {
				if (parseInt(res.data.code) === 401) {
					reject(new Error('token error'));
				} else {
					//延长token有效期
					setToken(res.data.data.token);
					resolve(res.data.data.rules.page);
					commit('SET_RULES', res.data.data.rules.component);
				}
			}).catch(error => reject(error));
		}))
	},
	logout() {
		setToken('');
	}
};

export default {
	// 开启命名空间
	// namespaced:true,
	state, getters, mutations, actions
}
